package com.bw.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.bw.ann.MyAnn;
import com.bw.domain.SysUser;
import com.bw.service.SysUserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author bobo棒
 * @date 2023年10月30日 11:02
 */

@RequestMapping("auth")
@RestController
public class AuthController {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SysUserService sysUserService;


    /**
     *每个用户每分钟只能生成一次，否则提示过于频繁。
     * @param uid
     * @return
     */
    @RequestMapping("check")
    public Result check(String uid){
        Long aLong = redisTemplate.opsForValue().increment("times" + uid, 1);
        if(aLong>1){
            return Result.fail("每个用户每分钟只能生成一次,请求过于频繁");
        }else{
            redisTemplate.expire("times" + uid,1,TimeUnit.SECONDS);//设置有效期1分钟
            return Result.success();
        }
    }



    @RequestMapping("createCode")
    public void createCode(String codeKey,HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());
        redisTemplate.opsForValue().set(codeKey,captcha.getCode(),2, TimeUnit.MINUTES);
    }


    @RequestMapping("login")
    public Result login(@RequestBody SysUser sysUser){
        //记录日志

        if(ObjectUtils.isEmpty(sysUser.getCode())){
            return Result.fail("必须输入验证码");
        }
        //比较验证码   //先从reds获取code
        String  codeRedis = (String) redisTemplate.opsForValue().get(sysUser.getCodeKey());
        if(!sysUser.getCode().equals(codeRedis)){
            return Result.fail("验证码不正确");
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(SysUser::getUsername,sysUser.getUsername());
        SysUser dbUser = sysUserService.getOne(wrapper);
        if(null ==dbUser){
            return Result.fail("用户不存在");
        }
        if(!dbUser.getPassword().equals(sysUser.getPassword())){
            return Result.fail("密码不正确");
        }

        String token = JWTUtils.createToken(dbUser.getId() + "", 60 * 3);
        return Result.success(token);

    }
}
